import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useAdminStore } from '../stores/admin'
import { isAdminTokenValid, clearAdminAuth } from '../utils/adminAuth'

export function useAdminAuth() {
  const adminStore = useAdminStore()
  const router = useRouter()

  // 检查管理员是否已登录且token有效
  const isAdminLoggedIn = computed(() => {
    // 先检查store中的基本信息
    const hasBasicInfo = !!(adminStore.adminInfo?.token && adminStore.adminInfo.role === 1)
    if (!hasBasicInfo) {
      return false
    }
    
    // 再检查token是否过期
    return isAdminTokenValid()
  })

  // 检查管理员token是否有效（同上，保持兼容性）
  const isAdminTokenValidComputed = computed(() => {
    return isAdminTokenValid()
  })

  // 获取管理员信息
  const adminInfo = computed(() => adminStore.adminInfo)

  // 要求管理员登录
  const requireAdminAuth = (message = '请先使用管理员账号登录') => {
    if (!isAdminTokenValidComputed.value) {
      ElMessage.warning(message)
      router.push('/admin/login')
      return false
    }
    return true
  }

  // 要求管理员权限
  const requireAdminRole = (message = '权限不足，需要管理员权限') => {
    if (!isAdminLoggedIn.value) {
      ElMessage.warning(message)
      router.push('/admin/login')
      return false
    }
    return true
  }

  // 管理员登出
  const adminLogout = () => {
    clearAdminAuth()
    adminStore.clearAdminInfo()  // 确保store也被清理
    ElMessage.success('已退出管理员登录')
    router.push('/admin/login')
  }

  // 检查并处理过期token
  const checkAndHandleExpiredToken = () => {
    if (!adminStore.checkExpire()) {
      ElMessage.warning('登录已过期，请重新登录')
      router.push('/admin/login')
      return false
    }
    return true
  }

  return {
    isAdminLoggedIn,
    isAdminTokenValidComputed,
    adminInfo,
    requireAdminAuth,
    requireAdminRole,
    adminLogout,
    checkAndHandleExpiredToken
  }
}
